import smtplib
import sys
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
import time

# 固定参数

sender = 'xxxxxx@xxxxx.com' #发送者邮箱账号
password = 'xxxxxxxxxxxx' #发送者邮箱密码
smtp_server = 'smtp.263.net' #邮箱服务器
receivers = ['xx@xx.com']  # 接受者邮箱 可以添加多个收件箱
class EmailSender:
    def __init__(self, sender, smtp_server, password):
        self.sender = sender
        self.smtp_server = smtp_server
        self.password = password
        self.server = None

    def connect(self):
        try:
            self.server = smtplib.SMTP(self.smtp_server, 25)
            self.server.set_debuglevel(0)  # 关闭调试模式
            self.server.starttls()
            self.server.login(self.sender, self.password)
            return True
        except Exception as e:
            print(f"连接到SMTP服务器失败，错误信息：{e}")
            return False

    def send_email(self, subject, attachments=None):
        msg = MIMEMultipart()
        msg['From'] = Header(self.sender, 'utf-8')
        msg['To'] = Header(", ".join(receivers), 'utf-8')
        msg['Subject'] = Header(subject, 'utf-8')

        body = '监测到有超差数据，请关注并查阅，命令行自动发送【监测超差0.10以上自动发送】'
        msg.attach(MIMEText(body, 'plain', 'utf-8'))

        if attachments:
            for attachment in attachments:
                try:
                    with open(attachment, 'rb') as f:
                        part = MIMEApplication(f.read(), Name=subject)
                        part['Content-Disposition'] = f'attachment; filename="{attachment}"'
                        msg.attach(part)
                except Exception as e:
                    print(f"读取附件 {attachment} 失败，错误信息：{e}")
                    return False

        try:
            self.server.sendmail(self.sender, receivers, msg.as_string())
            print(f"邮件发送成功！收件人：{', '.join(receivers)}")
            return True
        except Exception as e:
            print(f"邮件发送失败，错误信息：{e}")
            return False

    def quit(self):
        if self.server:
            self.server.quit()

def main():
    if len(sys.argv) < 2:
        print("用法: python send_email.py <邮件主题> [<附件1> [<附件2> ...]]")
        sys.exit(1)

    subject = sys.argv[1]
    attachments = sys.argv[2:]

    email_sender = EmailSender(sender, smtp_server, password)

    max_retries = 3
    retries = 0
    while retries < max_retries:
        if email_sender.connect():
            if email_sender.send_email(subject, attachments):
                email_sender.quit()
                sys.exit(0)
            else:
                email_sender.quit()
                retries += 1
                time.sleep(2)  # 等待2秒后重试
        else:
            retries += 1
            time.sleep(2)  # 等待2秒后重试
            
    sys.exit(1)

if __name__ == '__main__':
    main()